package com.pap.rabbitmq.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig implements InitializingBean {

	/**
	 * 交换器名字
	 */
	public static final String EXCHANGE_NAME = "exchange.log";

	/**
	 * 交换器名字 - 死信
	 */
	public static final String EXCHANGE_NAME_DEAD = "dead.exchange.log";

	/**
	 * 队列名字
	 */
	public static final String QUEUE_NAME_MSG = "queue.msg";

	/**
	 * 队列名字 - 死信
	 */
	public static final String QUEUE_NAME_MSG_DEAD = "dead.queue.msg";

	/**
	 * 路由Key
	 */
	public static final String ROUTING_KEY_MSG = "routing.msg.*";

	/**
	 * 路由Key - 死信
	 */
	public static final String ROUTING_KEY_MSG_DEAD = "dead.routing.msg.*";

	/**
	 * MQ管理代理
	 */
	@Autowired
	private AmqpAdmin amqpAdmin;

	/**
	 * 在这里 new DirectExchange()、 new Queue() 的时候，可以设置是否持久化 消息的持久化，默认是开启的(详见
	 * MessageProperties 类文件 MessageDeliveryMode.PERSISTENT;)
	 */
	@Override
	public void afterPropertiesSet() throws Exception {

		// 创建死信队列和死信交换机，并进行绑定
		Queue queueMsgDead = new Queue(QUEUE_NAME_MSG_DEAD, true);
		DirectExchange exchangeDead = new DirectExchange(EXCHANGE_NAME_DEAD, true, false);
		amqpAdmin.declareQueue(queueMsgDead);
		amqpAdmin.declareExchange(exchangeDead);
		amqpAdmin.declareBinding(BindingBuilder.bind(queueMsgDead).to(exchangeDead).with(ROUTING_KEY_MSG_DEAD));

		// 创建业务队列
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("x-dead-letter-exchange", EXCHANGE_NAME_DEAD);// 设置死信交换机
		map.put("x-dead-letter-routing-key", ROUTING_KEY_MSG_DEAD);// 设置死信routingKey
		// map.put("x-message-ttl", 5000);// 设置超时时间
		Queue queueMsg = new Queue(QUEUE_NAME_MSG, true, false, false, map);

		// 创建业务交换机
		DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);

		amqpAdmin.declareQueue(queueMsg);
		amqpAdmin.declareExchange(exchange);

		// 绑定业务队列和交换机，指定routingKey
		amqpAdmin.declareBinding(BindingBuilder.bind(queueMsg).to(exchange).with(ROUTING_KEY_MSG));

	}
}